import { createApp } from "vue";
import App from "./App.vue";

let app = null;

function render(props = {}) {
  const { container } = props;

  // 确保在微前端环境下有容器
  if (qiankunWindow.__POWERED_BY_QIANKUN__ && !container) {
    throw new Error("Container is required in qiankun environment");
  }

  app = createApp(App);

  // 确保挂载点存在
  const mountPoint = container
    ? container.querySelector("#sub-app")
    : "#sub-app";
  if (!mountPoint) {
    throw new Error("Mount point #sub-app not found");
  }

  app.mount(mountPoint);
}

// 使用 vite-plugin-qiankun 的帮助方法
import {
  renderWithQiankun,
  qiankunWindow,
} from "vite-plugin-qiankun/dist/helper";
renderWithQiankun({
  bootstrap() {
    console.log("[subApp] bootstrap");
  },
  mount(props) {
    console.log("[subApp] mount");
    render(props);
  },
  unmount() {
    console.log("[subApp] unmount");
    if (app) {
      app.unmount();
      if (app._container) {
        app._container.innerHTML = "";
      }
      app = null;
    }
  },
  update(props) {
    console.log("[subApp] update props", props);
  },
});

// 独立运行时
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  createApp(App).mount("#sub-app");
}
